package com.android.andtimer;

import android.app.Activity;
import android.os.Bundle;
import android.app.NotificationManager; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message;
import android.view.Window;
import android.view.WindowManager;
import android.view.KeyEvent; 
import android.view.Menu; 
import android.view.MenuItem;
import android.widget.Toast;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.Log;

public class AndTimer extends Activity
{

    private static final String TAG = "AndTimer";

    private static final int PREFERENCES_GROUP_ID = 0;
    private static final int MENU_ITEM_RESET = 0;


    protected static final int DEFAULTSECONDS = 60 * 1;  // 12 MInutes
//    protected static final int DEFAULTSECONDS = 60 * 12;  // 12 MInutes

     /* The value of these IDs is random! 
      * they are just needed to be recognized */ 
     protected static final int SECONDPASSEDIDENTIFIER = 0x1337; 
     protected static final int GUIUPDATEIDENTIFIER = 0x101; 
     protected static final int ANDTIMER_NOTIFICATION_ID = 0x1991;


     /** is the countdown running at the moment ?*/ 
     protected boolean running = false; 
     /** Seconds passed so far */ 
     protected int mySecondsPassed = 0; 
     /** Seconds to be passed totally */ 
     protected int mySecondsTotal = DEFAULTSECONDS;

    /* Thread that sends a message to the handler every second*/
    Thread myRefreshThread = null;

    // One View is all that we see.
    TimerView myTimerView = null;

    protected MediaPlayer mediaPlayer;

    /* The Handler that receives the messages 
     * sent out by myRefreshThread every second */
    Handler myTimerViewUpdateHandler = new Handler(){
        /** Gets called on every message that is received */
        // @Override
        public void handleMessage(Message msg) {
            //Log.d (TAG, "Receive message.");
            switch (msg.what) {
                case AndTimer.SECONDPASSEDIDENTIFIER:
                    // We identified the Message by its What-ID
                    if (running) {  
                        // One second has passed
                        mySecondsPassed++;
                        //Log.d (TAG, "mySecondsPassed = " + mySecondsPassed);
                        //Log.d (TAG, "mySecondsTotal = " + mySecondsTotal);
                        if(mySecondsPassed == mySecondsTotal){

                            myTimerView.updateSecondsPassed(mySecondsPassed);
                            myTimerView.updateSecondsTotal(mySecondsTotal);
                            myTimerView.invalidate();
 
                            //playSound (R.raw.on_time);

                            //Toast.makeText(AndTimer.this, R.string.timer_notification_text, Toast.LENGTH_SHORT).show();
                            running = false; 
                            mySecondsPassed = 0;
                            mySecondsTotal = 0;
                           
                            break;
                        }
                        
                    }
                    
                    // No break here --> runs into the next case
                case AndTimer.GUIUPDATEIDENTIFIER:
                    // Redraw AndTimerView !!
                    myTimerView.updateSecondsPassed(mySecondsPassed);
                    myTimerView.updateSecondsTotal(mySecondsTotal);
                    myTimerView.invalidate();
                    break;
            }
            super.handleMessage(msg);
        }
    };




    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.TYPE_STATUS_BAR,
                        WindowManager.LayoutParams.TYPE_STATUS_BAR);

        this.myTimerView = new TimerView(this);
        this.myTimerView.setBackgroundColor(0xFF000000);
        this.myTimerView.updateSecondsTotal(AndTimer.DEFAULTSECONDS);
        setContentView(this.myTimerView);
        //setContentView(R.layout.main);

        this.myRefreshThread = new Thread(new secondCountDownRunner());
        this.myRefreshThread.start();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // TODO Auto-generated method stub
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }

    }


    private void initializeMediaPlayer(int resId){
        mediaPlayer=MediaPlayer.create(this, resId);
        //mediaPlayer.prepareAsync();

        mediaPlayer.setOnCompletionListener(new OnCompletionListener(){
            public void onCompletion(MediaPlayer player) {
                releaseMediaPlayer();
            }
        });

    }

    private void releaseMediaPlayer(){
        if(mediaPlayer!=null){
            mediaPlayer.release();
            mediaPlayer=null;
        }
    }

    private void playSound(int resId){
        releaseMediaPlayer();
        initializeMediaPlayer(resId);
        mediaPlayer.start();
    }


    public boolean onCreateOptionsMenu(android.view.Menu menu) {

        super.onCreateOptionsMenu(menu);

        MenuItem item;

        item = menu.add(PREFERENCES_GROUP_ID, MENU_ITEM_RESET, 0, R.string.menu_reset);

        return true;
    }


    @Override
    public boolean onOptionsItemSelected (MenuItem item) {

        switch (item.getItemId()) {
            case MENU_ITEM_RESET:
                // Reset the counter and stop it
                this.mySecondsTotal = AndTimer.DEFAULTSECONDS;
                this.mySecondsPassed = 0;
                this.running = false;
                return true;
        }

        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Message m = new Message();
        m.what = AndTimer.GUIUPDATEIDENTIFIER;

        switch(keyCode){
            case KeyEvent.KEYCODE_DPAD_UP:

                if (!running) {
                    mySecondsPassed = 0;
                    mySecondsTotal += 10; 

                    if (mySecondsTotal >= 60 * 60)
                        mySecondsTotal = 0;
                }

                break;

            case KeyEvent.KEYCODE_DPAD_DOWN:

                if (!running) {
                    mySecondsPassed = 0;
                    mySecondsTotal -= 10; // Ten minute earlier

                    if (mySecondsTotal < 0)
                        mySecondsTotal = 60 * 60 + mySecondsTotal; // Ten minute earlier

                    Log.d (TAG, "keyDown:mySecondsTotal = " + mySecondsTotal);
                }
    
                break;

            case KeyEvent.KEYCODE_DPAD_CENTER:
                running = !running; 
                mySecondsTotal = mySecondsTotal - mySecondsPassed;
                mySecondsPassed = 0;
                releaseMediaPlayer();
                break;

            case KeyEvent.KEYCODE_DPAD_LEFT:

                if (!running) {

                    mySecondsPassed = 0;
                    Log.d (TAG, "KeyLeft before: mySecondsTotal = " + mySecondsTotal);
                    mySecondsTotal -= 1; // One second earlier

                    if (mySecondsTotal < 0)
                        mySecondsTotal = 60 * 60 + mySecondsTotal; 
    
                    Log.d (TAG, "KeyLeft after: mySecondsTotal = " + mySecondsTotal);
                }

                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:

                if (!running) {

                    mySecondsPassed = 0;
                    mySecondsTotal += 1; // One second later

                    if (mySecondsTotal >= 60 * 60)
                        mySecondsTotal = 0;
                }

                break;

            default:
                return super.onKeyDown(keyCode, event);
        }
        this.myTimerViewUpdateHandler.sendMessage(m);
        return true;
    }


    class secondCountDownRunner implements Runnable{
        // @Override
        public void run() {
            while(!Thread.currentThread().isInterrupted()){
                //Log.d (TAG, "Hi, I am counting down.");
                Message m = new Message();
                m.what = AndTimer.SECONDPASSEDIDENTIFIER;
                AndTimer.this.myTimerViewUpdateHandler.sendMessage(m);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }


}
